import * as crypto from "crypto";
import * as jwt from "jsonwebtoken";
import { sql } from "../util/db";

interface PlayLoad {
    openid: string
}

export async function genToken(playLoad: PlayLoad): Promise<string> {
    const key = genKey();
    const openid = playLoad.openid;
    const { rows } = await sql.query(`select count(1) from t_secret where openid=$1`, [openid]);
    const count = rows[0].count;
    if (count == 0) {
        sql.query('insert into t_secret(openid, key) values ($1, $2)', [openid, key])
            .catch(error => console.log(error));
    } else {
        sql.query('update t_secret set key=$1 where openid=$2', [key, openid])
            .catch(error => console.log(error));
    }
    return jwt.sign(playLoad, key);
}

export async function verify(token: string): Promise<boolean> {
    const playLoad = jwt.decode(token) as PlayLoad;
    const openid = playLoad ? playLoad.openid : "";
    if (!openid) {
        return false;
    }
    const { rows } = await sql.query('select key from t_secret where openid=$1', [openid])
    try {
        if (rows.length == 0) {
            return false;
        }
        jwt.verify(token, rows[0].key);
        return true;
    } catch (error) {
        console.log(error);
        return false;
    }
}

function genKey(): string {
    return crypto.randomBytes(256).toString('hex');
}